package com.itheima.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.BaseContext;
import com.itheima.pojo.OrderEasyExcel;
import com.itheima.pojo.Orders;
import com.itheima.pojo.R;
import com.itheima.service.OrdersService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrdersController {

    @Autowired
    OrdersService ordersService;

    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("/page")
    public R<IPage> userPage(Integer page, Integer pageSize, String number, String startTime, String endTime) {

        LambdaQueryWrapper<Orders> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.like(StringUtils.isNotEmpty(number), Orders::getId, number);
        lambdaQueryWrapper.ge(StringUtils.isNotEmpty(startTime), Orders::getOrderTime, startTime);
        lambdaQueryWrapper.le(StringUtils.isNotEmpty(endTime), Orders::getCheckoutTime, endTime);

        IPage<Orders> pa = new Page<>(page, pageSize);
        ordersService.page(pa, lambdaQueryWrapper);
        List<Orders> records = pa.getRecords();
        for (Orders record : records) {
            record.setUserName("用户:" + record.getId());
        }
        pa.setRecords(records);

        return R.success(pa);
    }

    @GetMapping("/export")
    public void export(HttpServletResponse resp) throws IOException {
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "状态:待付款");
        map.put(2, "状态:带派送");
        map.put(3, "状态:已派送");
        map.put(4, "状态:已完成");
        map.put(5, "状态:已取消");
        List<Orders> orders = ordersService.list();



        //创建存入的本地路径
        //String filename = "H://easyExcel/";
        //File file = new File(filename);
        //if (!file.isDirectory()){
        //    file.mkdirs();
        //}
        resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        resp.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("订单明细", "UTF-8").replaceAll("\\+", "%20");
        resp.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(resp.getOutputStream(), OrderEasyExcel.class).sheet("模板").doWrite(orders);

    }
}
